package com.lanbu.chat.service.impl;

import cn.hutool.core.util.StrUtil;
import com.lanbu.chat.service.IImFastGptService;
import com.lanbu.common.config.KnowledgeProperties;
import com.lanbu.common.constant.DeptConstants;
import com.lanbu.common.core.domain.entity.SysDept;
import com.lanbu.common.core.domain.entity.SysUser;
import com.lanbu.common.core.domain.vo.FastGptOpenapiVo;
import com.lanbu.common.utils.SecurityUtils;
import com.lanbu.system.domain.mongo.MongoOpenApis;
import com.lanbu.system.domain.mongo.MongoUsers;
import com.lanbu.system.domain.mongo.MongoTeamMembers;
import com.lanbu.system.service.ISysDeptService;
import com.lanbu.system.service.impl.MongoOpenApisService;
import com.lanbu.system.service.impl.MongoTeamMembersService;
import com.lanbu.system.service.impl.MongoUsersService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
public class ImFastGptServiceImpl implements IImFastGptService
{
    private final MongoUsersService mongoUsersService;

    private final KnowledgeProperties knowledgeProperties;

    private final MongoTeamMembersService mongoTeamMembersService;

    private final MongoOpenApisService mongoOpenApisService;

    private final ISysDeptService deptService;

    @Override
    public List<FastGptOpenapiVo> selectOpenapiList() {
        List<FastGptOpenapiVo> openApiVoList = new ArrayList<>();

        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysDept dept = user.getDept();
        String ancestors = dept.getAncestors();
        List<String> splitByAncestors = StrUtil.split(ancestors, ",");

        List<MongoOpenApis> openApisList = new ArrayList<>();
        // 查所有知识库(admin)
        if(user.isAdmin()){
            MongoUsers rootUser = Optional.ofNullable(mongoUsersService.findByUsername(knowledgeProperties.getRootName())).orElse(new MongoUsers());

            MongoTeamMembers teamMember = Optional.ofNullable(mongoTeamMembersService.findByUserId(rootUser.getId())).orElse(new MongoTeamMembers());
            List<MongoTeamMembers> teamMembers = Optional.ofNullable(mongoTeamMembersService.findByTeamId(teamMember.getTeamId())).orElse(new ArrayList<>());
            for (MongoTeamMembers member : teamMembers) {
                openApisList.addAll(Optional.ofNullable(mongoOpenApisService.findByTmbId(member.getId())).orElse(new ArrayList<>()));
            }
        }else{
            // todo 如果有管理知识库权限的并不是一级组织的人，则哪当前用户的 ancestors 的 第二个值去登录
            if(splitByAncestors.size() > DeptConstants.DEPT_UNION_FAST_GPT_DEEP){
                String s = splitByAncestors.get(DeptConstants.DEPT_UNION_FAST_GPT_DEEP);
                dept = deptService.selectDeptById(Long.valueOf(s));
            }
            MongoUsers rootUser = Optional.ofNullable(mongoUsersService.findByUsername(dept.getDeptId() + DeptConstants.DEPT_UNIQUE_SUFFIX_STR)).orElse(new MongoUsers());

            MongoTeamMembers teamMember = Optional.ofNullable(mongoTeamMembersService.findByUserId(rootUser.getId())).orElse(new MongoTeamMembers());
            openApisList.addAll(Optional.ofNullable(mongoOpenApisService.findByTmbId(teamMember.getId())).orElse(new ArrayList<>()));
        }

        List<FastGptOpenapiVo> collect = openApisList.stream().map(api -> {
            FastGptOpenapiVo fastGptAppKeyVo = new FastGptOpenapiVo();

            fastGptAppKeyVo.setId(String.valueOf(api.get_id()));
            fastGptAppKeyVo.setName(api.getName());
            fastGptAppKeyVo.setApiKey(api.getApiKey());

            return fastGptAppKeyVo;
        }).collect(Collectors.toList());
        return collect;
    }

}
